package zzjson.rabbitmq;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import zzjson.utils.ResourcesUtil;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : com.zzjson.rabbitmq</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年04月25日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class BaseRabbitMq {

	public static Channel getChannel() throws Exception {
		String key = ResourcesUtil.getKey("rabbitmq.uri");
		ConnectionFactory factory = new ConnectionFactory();
		factory.setUri(key);
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();
		return channel;
	}

	public static Connection getConn() {
		String key = ResourcesUtil.getKey("rabbitmq.uri");
		ConnectionFactory factory = new ConnectionFactory();
		try {
			factory.setUri(key);
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		Connection connection = null;
		try {
			connection = factory.newConnection();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
		return connection;
	}

	public static void close(Connection connection) {
		try {
			connection.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void close(Channel channel, Connection connection) {
		try {
			channel.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
		try {
			connection.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws IOException {
		Connection conn = getConn();
		Channel channel = conn.createChannel();
		HashMap hashMap = new HashMap();
		hashMap.put("id", 1);
		hashMap.put("name", "name");
		ObjectMapper objectMapper = new ObjectMapper();
		String s = objectMapper.writeValueAsString(hashMap);
		System.out.println(s);
		channel.basicPublish("boot-direct-exchange", "test", null, s.getBytes());
	}
}